﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Composite.Data;
using System.Transactions;
using Composite.Data.Transactions;
using LCA.Utils;

public partial class Admin_LCAFlow_ManageFlows : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ShowSearchFilter();
        }

        ctlPaginator.ControlToPaginate = ctlFlowList;

    }

    protected void btnCreateNew_Click(object sender, EventArgs e)
    {
        PageHelper.AdminPageRedirect(Page, "CreateFlow.aspx");
    }

    protected void ctlUserSearchFilter_SubmitClicked(object sender, System.EventArgs e)
    {
        ctlFlowList.SearchParameters = ctlFlowSearchFilter.SearchParameters;
        ShowResult();
    }

    private void ShowSearchFilter()
    {
        pnlSearchFilter.Visible = true;

        ctlFlowSearchFilter.Visible = true;

        pnlResult.Enabled = false;
        pnlResult.Visible = false;

        ctlPaginator.Visible = false;
        plhFooter.Visible = false;
    }

    private void ShowResult()
    {
        pnlSearchFilter.Visible = false;

        pnlResult.Enabled = true;
        pnlResult.Visible = true;

        ctlFlowList.RefreshComponents();

        ctlPaginator.ItemCount = ctlFlowList.GetItemCount();
        ctlPaginator.Visible = (ctlPaginator.ItemCount > 0);
        plhFooter.Visible = true;
    }

    protected void btnNewSearch_Click(object sender, EventArgs e)
    {
        PageHelper.AdminPageRedirect(Page, "ManageFlows.aspx");
    }

    protected void btnDeleteSelected_Click(object sender, EventArgs e)
    {
        IList<Guid> flowIds = ctlFlowList.GetSelectedIds();

        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
        {
            using (DataConnection connection = new DataConnection())
            {
                foreach (Guid flowId in flowIds)
                {
                    var flow = connection.Get<LCA.Data.Flow>().Where(f => f.Id == flowId).FirstOrDefault();
                    flow.IsDeleted = true;

                    connection.Update<LCA.Data.Flow>(flow);

                    //var flowFactors = connection.Get<LCA.Data.FlowFactor>().Where(ff => ff.Flow == flowId);
                    //foreach (LCA.Data.FlowFactor factor in flowFactors)
                    //{
                    //    factor.IsDeleted = true;
                    //    connection.Update<LCA.Data.FlowFactor>(factor);
                    //}
                }
               
            }

            transactionScope.Complete();
        }

        ctlFlowList.RefreshComponents();
    }
}